package com.easipass.exangeservice.msg;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 * 
 * @author itea
 * @date 2010-2-12
 * @version $Id$
 */
public class JDomMsg extends AbstractMsg {

	/** "JDomMsg.ATTR_DOCUMENT" */
	public static final String ATTR_DOCUMENT = "JDomMsg.ATTR_DOCUMENT";
	
	public JDomMsg() {}
	
	public JDomMsg(Msg msg) {
		copyAttributesFrom(msg);
	}
	
	public JDomMsg(Document doc) {
		setDocument(doc);
	}
	
	public static JDomMsg convertTextMsg(TextMsg msg) throws IOException, JDOMException {
		JDomMsg m = new JDomMsg();
		m.copyAttributesFrom(msg);
		m.setDocument(buildDocumentFromTextMsg(msg));
		return m;
	}
	
	public static JDomMsg convertRawMsg(RawMsg msg, String encoding) throws IOException, JDOMException {
		JDomMsg m = new JDomMsg();
		m.copyAttributesFrom(msg);
		m.setDocument(buildDocumentFromRawMsg(msg, encoding));
		return m;
	}
	
	public void setDocument(Document doc) {
		setAttribute(ATTR_DOCUMENT, doc);
	}
	
	public Document getDocument() {
		return getAttribute(ATTR_DOCUMENT);
	}
	
	public void outputTo(TextMsg msg) throws IOException {
		String encoding = msg.getEncoding() == null ? "UTF-8" : msg.getEncoding();
		outputTo(msg, encoding);
	}
	
	public void outputTo(RawMsg msg, String encoding) throws IOException {
		OutputStream out = null;
		try {
			out = msg.openOutputStream();
			outputTo(out, encoding);
		} finally {
			if(out != null) out.close();
		}
	}
	
	public void outputTo(OutputStream out, String encoding) throws IOException {
		Document doc = getDocument();
		if(doc == null) return; // do nothing;
		
		XMLOutputter p = new XMLOutputter();
		Format format = Format.getPrettyFormat();
		format.setEncoding(encoding);
		p.setFormat(format);
		p.output(doc, out);
	}
	
	public static Document buildDocumentFromRawMsg(RawMsg msg, String encoding)
	throws IOException, JDOMException {
		InputStreamReader in = null;
		SAXBuilder b = new SAXBuilder();
		try {
			in = new InputStreamReader(msg.openInputStream(), encoding);
			return b.build(in);
		} finally {
			if(in != null) in.close();
		}
	}
	
	public static Document buildDocumentFromTextMsg(TextMsg msg)
	throws IOException, JDOMException {
		Reader in = null;
		SAXBuilder b = new SAXBuilder();
		try {
			in = msg.openReader();
			return b.build(in);
		} finally {
			if(in != null) in.close();
		}
	}
}
